import React, { Component } from "react";
import "./Screen.css";
export default class Fetch extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.redundantRequests = 0;
    this.successfulRequests = 0;
    this.controller = null;
  }

  componentDidMount() {}
  _onChange = () => {
    console.log("%c%s", "color: #f2b6e3", this.inputRef.current.value);
    this._fetch();
  };

  _fetch = () => {
    const _this = this;
    var fakeApi =
      "http://mock.52react.cn/mock/5d886f166cacdb72c1cb5fea/example/upload";

    var auto = document.getElementById("autocomplete");

    auto.addEventListener("keydown", function(event) {
      if (this.controller) {
        this.controller.abort();
      }
      if (AbortController) {
        this.controller = new AbortController();
        var signal = this.controller.signal;
      }

      console.log("%c%s", "color: #00a3cc", this);
      console.log(
        "%c%s",
        "color: #00e600",
        _this.redundantRequests,
        _this.successfulRequests
      );

      fetch(fakeApi, { signal })
        .then(function(response) {
          response.json().then(data => {
            console.log("response", response);
            _this.successfulRequests++;
            document.getElementById("successful").textContent =
              _this.successfulRequests + " requests have been successful";
            //document.getElementById("autocompleteMenu").textContent = data.value;
            //document.getElementById("error").textContent = "";
          });
        })
        .catch(function(e) {
          // Discount for NetworkErrors etc
          if (e.name === "AbortError") {
            _this.redundantRequests++;
            document.getElementById("redundant").textContent =
              _this.redundantRequests + " uneccessary requests cancelled";
            document.getElementById("error").textContent =
              "Cancelled request for " + event.target.value;
          }
        });
    });
  };

  render() {
    let main = <>
      <main>
        <h1> Abortable Fetch Example </h1>
        <h3> Type quickly to see request cancelled! </h3>
        <input
            id="autocomplete"
            ref={this.inputRef}
            onChange={this._onChange}
        />
        <div id="autocompleteMenu"/>
        <div id="successful"/>
        <div id="redundant"/>
        <div id="error"/>
      </main>
    </>;
    return main;
  }
}
